package com.spring.quartz.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * <h3>partitionjob</h3>
 * <p>DemoTaskScheduler</p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2019-12-17 18:11
 **/
@Component
public class DemoTaskScheduler {
    private static Log LOG = LogFactory.getLog(DemoTaskScheduler.class);

    /**
     * 注入调度器
     */
    @Autowired
    SchedulerFactoryBean schedulerFactoryBean;

    @Autowired
    private Scheduler scheduler;

    @PostConstruct
    public void init() {
        try {
            JobDetail jobDetail = JobBuilder.newJob(JobDemoService.class)
                    .withIdentity("job", "test")
                    .build();
            String cron = "0/2 * * * * ?";
            jobDetail.getJobDataMap().put("cron", cron);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger", "t1")
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                    .build();
            //将任务和触发器绑定
            scheduler.scheduleJob(jobDetail, trigger);
            //启动一个任务
            scheduler.start();
            LOG.info("任务初始化成功!");
        } catch (Exception e) {
            LOG.error("", e);
        }
    }

    public void addJob(String jobName, String groupJobName, String triggerName
                            , String triggerGroupName, Class clazz, String cron) {
        scheduler = schedulerFactoryBean.getScheduler();
        JobDetail jobDetail = JobBuilder.newJob(clazz)
                .withIdentity(jobName, groupJobName)
                .build();
        TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
        triggerBuilder.withIdentity(triggerName, triggerGroupName);
        triggerBuilder.startNow();

        triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
        CronTrigger trigger = (CronTrigger) triggerBuilder.build();
        try {
            scheduler.scheduleJob(jobDetail, trigger);
            if(!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
            LOG.error("添加任务出现异常: {}", e);
        }
    }




}
